package com.chen10.gobang.service.impl;

import com.chen10.gobang.common.enums.response.ErrorEnum;
import com.chen10.gobang.common.exception.BusinessException;
import com.chen10.gobang.mapper.GameRecordsMapper;
import com.chen10.gobang.model.dto.GameRecordsPageDTO;
import com.chen10.gobang.model.page.Pager;
import com.chen10.gobang.model.pojo.GameRecords;
import com.chen10.gobang.model.vo.GameRecordsVO;
import com.chen10.gobang.service.GameRecordsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class GameRecordsServiceImpl implements GameRecordsService {
    @Resource
    private GameRecordsMapper gameRecordMapper;

    @Override
    public Pager<GameRecordsVO> getRecordsPageByUserId(GameRecordsPageDTO gameRecordsPageDTO) {
        //校验参数
        if (gameRecordsPageDTO == null) {
            throw new BusinessException(ErrorEnum.PARAM_ERROR);
        }
        int page = gameRecordsPageDTO.getPage();
        int size = gameRecordsPageDTO.getSize();
        int userId = gameRecordsPageDTO.getUserId();

        if (page <= 0 || size <= 0 || userId <= 0) {
            throw new BusinessException(ErrorEnum.PARAM_ERROR);
        }

        int offset = (page - 1) * size;  // 计算分页的起始位置
        long total = gameRecordMapper.getCountsByUserId(userId); // 查询总记录数

        // 获取分页数据
        List<GameRecordsVO> records = gameRecordMapper.getPageByUserId(userId, offset, size);

        Pager<GameRecordsVO> pager = new Pager<>();
        pager.setPage(page);
        pager.setSize(size);
        pager.setTotal(total);
        pager.setData(records);
        return pager;
    }
}
